package com.kuang.future;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author luomingliang
 * @date 2021/5/26 20:05
 */
public class Demo1 {
    @Test
    public void test001() throws ExecutionException, InterruptedException {
        //没有返回值的异步回调
        CompletableFuture<Void> future = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "runAsync==>Void");
        });
        System.out.println("111111");
        future.get();//获取执行结果
        System.out.println("222222");
    }

    @Test
    public void test002() throws ExecutionException, InterruptedException {
        //有返回值的异步回调
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            int i = 1/0;
            System.out.println(Thread.currentThread().getName()+ "supplyAsync==>Integer");
            return 1024;
        });

        Integer result = future.whenComplete((t, u) -> {
            System.out.println("t=>" + t); //正常的返回结果
            System.out.println("u=>" + u); //错误信息
        }).exceptionally(e -> {
            System.out.println(e.getMessage());
            return 404; //可以获取到错误的返回结果
        }).get();
        System.out.println(result);
    }
}
